package com.example.librarymanagement.controller;

import com.example.librarymanagement.mapper.BorrowRecordMapper;
import com.example.librarymanagement.model.Book;
import com.example.librarymanagement.model.BorrowRecord;
import com.example.librarymanagement.service.BookService;
import com.example.librarymanagement.service.BorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class BookController {

    private final BookService bookService;
    private final BorrowRecordService borrowRecordService;
    @Autowired
    private BorrowRecordMapper borrowRecordMapper;

    @Autowired
    public BookController(BookService bookService, BorrowRecordService borrowRecordService) { // 修改构造函数以自动装配
        this.bookService = bookService;
        this.borrowRecordService = borrowRecordService; // 设置BorrowRecordService
    }


    // 获取图书信息
    @GetMapping("/api/v1/books/{bookId}")
    public Book getBookById(@PathVariable("bookId") Integer id) {

        return bookService.getBookById(id);
    }
    @GetMapping("/api/v1/books")
    public List<Book> listBooks() {
        return bookService.listBooks();
    }

    // 获取所有图书
    public List<Book> listBooks(
            @RequestParam(value = "bookName", required = false) String bookName,
            @RequestParam(value = "author", required = false) String author,
            @RequestParam(value = "category", required = false) String category) {
        Map<String, Object> conditions = new HashMap<>();
        if (bookName != null)
            conditions.put("bookName", bookName);
        if (author != null)
            conditions.put("author", author);
        if (category != null)
            conditions.put("category", category);

        return bookService.queryBooksByConditions(conditions);
    }

    // 添加新图书
    @PostMapping("/api/v1/books")
    public ResponseEntity<Book> addBook(@RequestBody Book book) {
        Book addedBook = bookService.addBook(book);
        return new ResponseEntity<>(addedBook, HttpStatus.CREATED);
    }

    // 更新图书信息
    @PatchMapping("/api/v1/books/{bookId}")
    public Book updateBook(@PathVariable("bookId") Integer bookId, @RequestBody Map<String, Object> updateFields) {
        return bookService.updateBook(bookId, updateFields);
    }

    // 删除图书
    @DeleteMapping("/api/v1/books/{bookId}")
    public ResponseEntity deleteBook(@PathVariable("bookId") Integer bookId) {
        Book book = bookService.getBookById(bookId);
        bookService.deleteBook(bookId);
        return new ResponseEntity(HttpStatus.OK);
    }
    @PostMapping("/api/v1/books/{bookId}/borrow")
    public ResponseEntity<?> borrowBook(@PathVariable Integer bookId, @RequestParam Integer userId) {
        Book book = bookService.getBookById(bookId); // 根据bookId获取图书信息

        if (book.getTotalStock() <= 0) {
            // 如果库存为0或以下，则返回错误信息
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无法借书，库存不足。");
        }

        try {
            BorrowRecord record = borrowRecordService.createBorrowRecord(bookId, userId);
            // 借书成功后，更新图书的库存和借出次数
            bookService.updateBookAfterBorrow(bookId);
            return ResponseEntity.ok(record);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    @GetMapping("/api/v1/borrow-records/{userId}")
    public List<BorrowRecord> listBorrowedBooks(@PathVariable Integer userId) {
        return borrowRecordMapper.selectByUserId(userId);
    }

    @PostMapping("/api/v1/borrow-records/{recordId}/return")
    public ResponseEntity<?> returnBook(@PathVariable Integer recordId, @RequestParam Integer userId, @RequestParam Integer bookId) {
        try {
            borrowRecordService.returnBook(recordId, userId);
            bookService.returnBook(bookId);
            return ResponseEntity.ok("归还成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    @GetMapping("/api/v1/borrow-records/list-all")
    public ResponseEntity<List<BorrowRecord>> listAllBorrowRecords() {
        List<BorrowRecord> records = borrowRecordService.listAllBorrowRecords();
        return ResponseEntity.ok(records);
    }

    @GetMapping("/api/v1/users/{userId}/borrow-records/list")
    public ResponseEntity<List<BorrowRecord>> listBorrowRecordsByUser(@PathVariable Integer userId) {
        List<BorrowRecord> records = borrowRecordService.listBorrowRecordsByUser(userId);
        return ResponseEntity.ok(records);
    }
    @GetMapping("/api/v1/books/search")
    public ResponseEntity<List<Book>> searchBooks(
            @RequestParam(value = "bookName", required = false) String bookName,
            @RequestParam(value = "author", required = false) String author,
            @RequestParam(value = "category", required = false) String category) {
        Map<String, String> searchCriteria = new HashMap<>();
        if (bookName != null) {
            searchCriteria.put("bookName", bookName);
        }
        if (author != null) {
            searchCriteria.put("author", author);
        }
        if (category != null) {
            searchCriteria.put("category", category);
        }

        List<Book> foundBooks = bookService.searchBooks(searchCriteria);
        return ResponseEntity.ok(foundBooks);
    }
    @GetMapping("/api/v1/books/borrow-rank")
    public ResponseEntity<List<Book>> listBorrowRankBooks() {
        List<Book> rankedBooks = bookService.listBorrowRankBooks();
        return ResponseEntity.ok(rankedBooks);
    }

}